{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import requests\n",
    "from playsound import playsound"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "headers = {\n",
    "    'Origin': 'https://y.qq.com',\n",
    "    'Referer': 'https://y.qq.com/portal/search.html',\n",
    "    'Sec-Fetch-Mode': 'cors',\n",
    "    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'\n",
    "}"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "#########################################\n",
    "# 搜索格式：陈奕迅 十年\n",
    "#########################################\n",
    "def search_music(singer='', song_name=''):\n",
    "    search_context = singer.strip() + ' ' + song_name.strip()\n",
    "    PAGE = 1  # 返回第1页\n",
    "    NUM = 10  # 返回10条结果\n",
    "    music_info_list = []\n",
    "    search_url = f'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p={PAGE}&n={NUM}&w={search_context}'\n",
    "    response = requests.get(url=search_url).text\n",
    "    music_json = response[9:-1]\n",
    "    music_data = json.loads(music_json)\n",
    "\n",
    "    music_list = music_data['data']['song']['list']\n",
    "    for music in music_list:\n",
    "        if 'media_mid' in music:\n",
    "            music_name = music['songname']  # 歌曲的名字\n",
    "            singer_name = music['singer'][0]['name']  # 歌手的名字\n",
    "            songmid = music['songmid']\n",
    "            media_mid = music['media_mid']\n",
    "            music_info_list.append((music_name, singer_name, songmid, media_mid))\n",
    "    return music_info_list"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [],
   "source": [
    "# 获取vkey\n",
    "def get_purl(music_info_list):\n",
    "    music_data = []\n",
    "    for music in music_info_list:\n",
    "        music_name = music[0]\n",
    "        singer_name = music[1]\n",
    "        songmid = music[2]\n",
    "        url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={\"req\":{\"module\":\"CDN.SrfCdnDispatchServer\",\"method\":\"GetCdnDispatch\",\"param\":{\"guid\":\"8846039534\",\"calltype\":0,\"userip\":\"\"}},\"req_0\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"8846039534\",\"songmid\":[\"%s\"],\"songtype\":[0],\"uin\":\"1152921504784213523\",\"loginflag\":1,\"platform\":\"20\"}},\"comm\":{\"uin\":\"1152921504784213523\",\"format\":\"json\",\"ct\":24,\"cv\":0}}' % songmid\n",
    "        response = requests.get(url).json()  # 如果你获取的数据 是 {}  .json() 他会直接帮我们转换成字典\n",
    "        purl = response['req_0']['data']['midurlinfo'][0]['purl']\n",
    "        full_media_url = 'http://dl.stream.qqmusic.qq.com/' + purl\n",
    "        music_data.append(\n",
    "            {\n",
    "                'music_name': music_name,\n",
    "                'singer_name': singer_name,\n",
    "                'full_media_url': full_media_url\n",
    "            }\n",
    "        )\n",
    "    return music_data"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [],
   "source": [
    "# 返回搜索结果第一首歌的，下载链接\n",
    "def get_first_song_download(music_data):\n",
    "    for music in music_data:\n",
    "        if '.m4a' in music['full_media_url']:\n",
    "            return music"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "# 保存到本地\n",
    "def save_music_mp3(music):\n",
    "    if not os.path.exists('cache'):  # 判断是否有歌曲下载文件夹\n",
    "        os.mkdir('cache')  # 如果没有创建 歌曲下载文件夹\n",
    "    music_name = music['music_name']\n",
    "    singer_name = music['singer_name']\n",
    "    full_url = music['full_media_url']\n",
    "    music_response = requests.get(full_url, headers=headers).content\n",
    "    with open('cache/%s-%s.mp3' % (singer_name, music_name), 'wb') as fp:\n",
    "        fp.write(music_response)\n",
    "        print('[%s]保存成功！' % music_name)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[孤勇者]保存成功！\n"
     ]
    }
   ],
   "source": [
    "music_info_list = search_music(singer=\"陈奕迅\")\n",
    "music_data = get_purl(music_info_list)\n",
    "res = get_first_song_download(music_data)\n",
    "save_music_mp3(res)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}